<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="6">
                <div class="grid-content bg-purple">
                    <div style="margin-bottom: 20px;margin-top: 20px">
                        <el-button
                                round
                                type="primary"
                                plain
                                size="medium"
                                @click="dialogInputVisible = true"
                        >
                            添加分类<i class="el-icon-plus"></i>
                        </el-button>

                        <el-dialog title="请输入分类名称" :visible.sync="dialogInputVisible" width="30%" :modal="false">
                            <el-input
                                    placeholder="请输入内容"
                                    v-model="categoryName"
                                    clearable>
                            </el-input>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="dialogInputVisible = false">取 消</el-button>
                                <el-button type="primary" @click="handleConfirm">确 定</el-button>
                            </span>
                        </el-dialog>
                    </div>
                </div>
            </el-col>
            <el-col :span="4">
                <div class="grid-content bg-purple">
                    <div class="demo-input-suffix" style="margin-bottom: 20px;margin-top: 20px">
                        <el-input
                                size="medium "
                                placeholder="请输入内容"
                                prefix-icon="el-icon-search"
                                v-model="input">
                        </el-input>
                    </div>
                </div>
            </el-col>
            <el-col :span="6">
                <el-button
                        type="primary"
                        size="medium"
                        icon="el-icon-search"
                        round
                        plain
                        style="margin-bottom: 20px;margin-top: 20px">
                    搜索
                </el-button>
            </el-col>
            <el-col :span="6" >
                <div class="grid-content bg-purple">
                    <div style="margin-bottom: 20px;margin-top: 20px">
                        <el-button
                                round
                                type="primary" plain
                                size="medium"
                                @click="productDialogVisible=true"
                        >
                            添加产品<i class="el-icon-plus"></i>
                        </el-button>
                        <el-dialog
                                title="添加产品"
                                :visible.sync="productDialogVisible"
                                width="50%">
                            <el-form :model="productForm" :rules="rules" ref="productForm" label-width="100px" class="demo-ruleForm">
                                <el-form-item label="产品名称" prop="name">
                                    <el-input v-model="productForm.name" placeholder="请输入产品名称，长度为2到15字符"></el-input>
                                </el-form-item>
                                <el-form-item label="产品价格" prop="price">
                                    <el-input type="age" v-model.number="productForm.price" autocomplete="off" placeholder="请输入产品价格"></el-input>
                                </el-form-item>
                                <el-form-item label="产品状态" prop="status">
                                    <el-select v-model="productForm.status" placeholder="请选择产品状态">
                                        <el-option label="上架" value="1"></el-option>
                                        <el-option label="下架" value="0"></el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="产品类别" prop="category">
                                    <el-select v-model="productForm.category" placeholder="请选择">
                                        <el-option
                                                v-for="item in tabCategory"
                                                :key="item.id"
                                                :label="item.name"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="产品图片" prop="photo">
                                    <el-upload
                                            class="avatar-uploader"
                                            action="http://localhost:8080/jz/product/uploadPhoto"
                                            :show-file-list="false"
                                            :on-success="handleAvatarSuccess"
                                            >
                                        <img v-if="productForm.photo" :src="productForm.photo" class="avatar">
                                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item label="产品视频" prop="video">
                                    <el-upload
                                            class="avatar-uploader"
                                            action="http://localhost:8080/jz/product/uploadVideo"
                                            :show-file-list="false"
                                            :on-success="handleAvatarSuccess3"
                                    >
                                        <div v-if="productForm.video" >已上传</div>
                                        <div v-else>
                                            <el-button  size="small" type="primary">点击上传</el-button>
                                            <div slot="tip" class="el-upload__tip">只能上传mp4文件，且不超过100M</div>
                                        </div>
                                    </el-upload>
                                </el-form-item>
                                <el-form-item label="产品描述" prop="desc">
                                    <el-input type="textarea" v-model="productForm.desc"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="submitForm('productForm')">确定</el-button>
                                    <el-button @click="productDialogVisible = false">取消</el-button>
                                </el-form-item>
                            </el-form>
                        </el-dialog>
                    </div>
                </div>
            </el-col>

        </el-row>
        <el-tabs v-model="editableTabsValue" type="card"   @tab-click="handleClick">
            <el-tab-pane label="全部分类" name="0">
                <el-table
                        stripe
                        :data="allCategory"
                        style="width: 50%;margin-left: 350px">
                    <el-table-column
                            label="分类编号"
                            align="center"
                            width="180">
                        <template slot-scope="scope">
                            <span style="margin-left: 10px">{{ scope.row.number }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="分类名称"
                            align="center"
                            width="180">
                        <template slot-scope="scope">
                                <div slot="reference" class="name-wrapper">
                                    <el-tag size="medium">{{ scope.row.name }}</el-tag>
                                </div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="操作"
                            align="center"
                            width="180">
                        <template slot-scope="scope">
                                <el-button
                                        circle
                                        icon="el-icon-edit"
                                        size="mini"
                                        @click="handleEdit( scope.row)">
                                </el-button>
                                <el-dialog width="20%" title="请修改分类名称" :modal="false" :visible.sync="dialogVisible1">
                                    <el-input
                                            placeholder="请输入修改后的分类名称"
                                            v-model="modifyCaName"
                                            clearable>
                                    </el-input>
                                    <span slot="footer" class="dialog-footer">
                                    <el-button @click="dialogVisible1 = false">取 消</el-button>
                                    <el-button type="primary" @click="modifyCategoryName">确 定</el-button>
                                </span>
                                </el-dialog>
                                <el-button
                                        circle
                                        icon="el-icon-delete"
                                        size="mini"
                                        type="danger"
                                        @click="deleteCategory(scope.row)">
                                </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                        small
                        layout="prev, pager, next"
                        style="margin-left: 500px;margin-top: 20px "
                        :page-size="7"
                        @current-change="page"
                        :total="total"
                        >
                </el-pagination>
            </el-tab-pane>
            <el-tab-pane
                    v-for="(item, index) in tabCategory"
                    :key="item.number"
                    :label="item.name"
                    :name="item.number">
                <div v-if="productList&&productList.length>0">
                    <el-table
                            stripe
                            :data="productList"
                            style="width: 100%">
                        <el-table-column type="expand">
                            <template slot-scope="props">
                                <el-form label-position="left" inline class="demo-table-expand">
                                    <el-form-item label="产品编号">
                                        <span>{{ props.row.productNumber }}</span>
                                    </el-form-item>
                                    <el-form-item label="产品名称">
                                        <span>{{ props.row.name }}</span>
                                    </el-form-item>
                                    <el-form-item label="价格">
                                        <span>{{ props.row.price }}</span>
                                    </el-form-item>
                                    <el-form-item label="销量">
                                        <span>{{ props.row.sales }}</span>
                                    </el-form-item>
                                    <el-form-item label="产品状态">
                                        <span v-if="props.row.status==1"><el-tag type="success">已上架</el-tag></span>
                                        <span v-else><el-tag type="danger">已下架</el-tag></span>
                                    </el-form-item>
                                    <el-form-item label="产品图片">
                                        <img :src="props.row.photo" height="28px" width="28px" style="padding: 2px"/>
                                    </el-form-item>
                                    <el-form-item label="商品描述">
                                        <span>{{ props.row.introduce }}</span>
                                    </el-form-item>
                                </el-form>
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="产品编号"
                                prop="productNumber"
                                align="center">
                        </el-table-column>
                        <el-table-column
                                label="产品名称"
                                prop="name"
                                align="center">
                        </el-table-column>
                        <el-table-column
                                align="center"
                                label="图片"
                                width="180">
                            <template slot-scope="scope">
                                <div slot="reference" class="name-wrapper">
                                    <img :src="scope.row.photo" height="28px" width="28px" style="padding: 2px"/>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="价格"
                                align="center">
                            <template slot-scope="scope">
                                <div slot="reference" class="name-wrapper">
                                    <el-tag size="medium">{{ scope.row.price }}</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                                label="销量"
                                prop="sales"
                                align="center">
                        </el-table-column>
                        <el-table-column
                                label="产品状态"
                                prop="status"
                                align="center">
                            <template  slot-scope="scope">
                                <span v-if="scope.row.status==1"><el-tag type="success">已上架</el-tag></span>
                                <span v-else><el-tag type="danger">已下架</el-tag></span>
                            </template>
                        </el-table-column>
                        <el-table-column
                                align="left">
                            <template slot="header" >
                               操作
                            </template>
                            <template slot-scope="scope">
                                <span v-if="scope.row.status==1">
                                    <el-button
                                            circle
                                            type="primary"
                                            size="mini"
                                            disabled>
                                        上架
                                    </el-button>
                                    <el-button
                                            circle
                                            type="warning"
                                            size="mini"
                                            @click="changeProductStatus( scope.row)">
                                        下架
                                    </el-button>
                                </span>
                               <span v-else>
                                   <el-button
                                           circle
                                           type="primary"
                                           size="mini"
                                           @click="changeProductStatus( scope.row)">
                                       上架
                                   </el-button>
                                   <el-button
                                           circle
                                           type="warning"
                                           size="mini"
                                           disabled>
                                       下架
                                   </el-button>
                               </span>
                                <el-button
                                        circle
                                        icon="el-icon-edit"
                                        size="mini"
                                        @click="editProduct(scope.row)">
                                </el-button>
                                <el-dialog width="50%" title="修改产品" :modal="false" :visible.sync="dialogVisible2">
                                    <el-form :model="newProductForm" :rules="rule" ref="newProductForm" label-width="100px" class="demo-ruleForm">
                                        <el-form-item label="产品名称" prop="name">
                                            <el-input v-model="newProductForm.name" ></el-input>
                                        </el-form-item>
                                        <el-form-item label="产品价格" prop="price">
                                            <el-input type="age" v-model.number="newProductForm.price" autocomplete="off" placeholder="请输入产品价格"></el-input>
                                        </el-form-item>
                                        <el-form-item label="产品状态" prop="status">
                                            <el-select v-model="defaultStatus" placeholder="请选择产品状态" @change="statusChange">
                                                <el-option label="上架" value="1"></el-option>
                                                <el-option label="下架" value="0"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="产品类别" prop="caid">
                                            <el-select v-model="defaultCategory" placeholder="请选择" @change="categoryChange">
                                                <el-option
                                                        v-for="item in tabCategory"
                                                        :key="item.id"
                                                        :label="item.name"
                                                        :value="item.id">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="产品图片">
                                            <el-upload
                                                    class="avatar-uploader"
                                                    action="http://localhost:8080/jz/product/uploadPhoto"
                                                    :show-file-list="false"
                                                    :on-success="handleAvatarSuccess2"
                                            >
                                                <img  :src="newProductForm.photo" class="avatar">
                                                <i>点击图片进行更换</i>
                                            </el-upload>
                                        </el-form-item>
                                        <el-form-item label="产品描述" prop="desc">
                                            <el-input type="textarea" v-model="newProductForm.introduce"></el-input>
                                        </el-form-item>
                                        <el-form-item>
                                            <el-button type="primary" @click="submitNewForm('newProductForm')">确定</el-button>
                                            <el-button @click="dialogVisible2 = false">取消</el-button>
                                        </el-form-item>
                                    </el-form>
                                </el-dialog>
                                <el-button
                                        circle
                                        icon="el-icon-delete"
                                        size="mini"
                                        type="danger"
                                        @click="deleteProduct(scope.row)">
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div v-else>
                    <el-empty description="该分类下尚无产品"></el-empty>
                </div>
                <el-pagination
                        small
                        layout="prev, pager, next"
                        :page-size="7"
                        @current-change="productPage"
                        :total="productTotal"
                >
                </el-pagination>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
    export default {
        name: "category",
        // inject: ['reload'],
        data() {
            return {
                input:'',//搜索框输入内容
                dialogInputVisible:false,
                dialogVisible1:false, //修改分类名称时弹出框
                dialogVisible2:false, //修改产品弹出框
                productDialogVisible:false,//添加产品弹出框
                categoryName:'',//添加时输入的分类名称
                modifyCaName:'',//修改时输入的分类名称
                rowNumber:'', //修改、删除分类名称时的分类编号
                editableTabsValue: '0', //为0，默认指向全部分类标签
                tabIndex: 0,
                total:null,  //全部分类表的总条数
                productTotal:null, //分页查询产品的总条数
                value:'', //选择产品分类时的value
                tabCategory:[], //所有类别
                allCategory:[], //分页获取的类别
                categoryNumber:'', //分页查询产品时的分类编号
                defaultCategory:'',//修改产品时绑定默认类别
                defaultStatus:'', //修改产品时默认状态
                searchProduct:'',//查找产品时的输入值
                productList: [],
                productForm:{},  //添加产品时提交的表单
                newProductForm:{}, //修改产品时的表单
                rules: {
                    name: [
                        { required: true, message: '请输入产品名称', trigger: 'blur' },
                        { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
                    ],
                    price: [
                        { required: true, message: '价格不能为空'},
                        { type: 'number', message: '价格必须为整数'}
                    ],
                    desc: [
                        { required: true, message: '请填写产品描述', trigger: 'blur' }
                    ]
                },
                rule: {
                    name: [
                        { required: true, message: '请输入产品名称', trigger: 'blur' },
                        { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
                    ],
                    price: [
                        { required: true, message: '价格不能为空'},
                        { type: 'number', message: '价格必须为整数'}
                    ],
                    desc: [
                        {trigger: 'blur' }
                    ]
                },

            }
        },

        created() {
            var that=this;
            this.$ajax.post('/jz/category/getAllCategory').then(function (resp) {
                that.tabCategory=resp.data.categoryList;
                that.tabIndex=resp.data.categoryList.length;
            })
            this.page(1);
        },

        methods: {
            addTab(targetName,number) {
                let newTabNumber = ++this.tabIndex + '';
                this.tabCategory.push({
                    name: targetName,
                    number: number
                });
                this.editableTabsValue = newTabNumber;
            },

            handleClick(tab) {
                if(tab.$options.propsData.name=='0'){
                    this.page(1);
                }
                else{
                    console.log(tab.$options.propsData);
                    this.categoryNumber=tab.$options.propsData.name;
                    var that=this;
                    this.$ajax.post('/jz/product/getProductByCategoryAndPage?number='+tab.$options.propsData.name+'&currentPage=1').then(function (resp) {
                        console.log(resp.data);
                        if(resp.data.status==200){
                            that.productTotal=resp.data.totalCount;
                            that.productList=resp.data.productList;
                        }
                        if(resp.data.status==204){
                            that.$message.error('该分类下尚无产品，请添加！');
                            that.productList=resp.data.productList;
                        }
                    })
                }
            },

            productPage(currentPage){
                var that=this;
                this.$ajax.post('/jz/product/getProductByCategoryAndPage?number='+this.categoryNumber+'&currentPage='+currentPage).then(function (resp) {
                    console.log(resp.data);
                    if(resp.data.status==200){
                        that.productTotal=resp.data.totalCount;
                        that.productList=resp.data.productList;
                    }
                    if(resp.data.status==204){
                        that.$message.error('该分类下尚无产品，请添加！');
                        that.productList=resp.data.productList;
                    }
                })
            },

            handleConfirm(){
                this.dialogVisible=false;
                var that=this;
                this.$ajax.post('/jz/category/addCategory?name='+this.categoryName).then(function (resp) {
                    //console.log(resp.data);
                    if(resp.data.status==200){
                        that.addTab(that.categoryName,resp.data.number);
                    }
                })
            },

            handleEdit(row) {
                this.dialogVisible1=true;
                this.modifyCaName=row.name;
                this.rowNumber=row.number;
                //console.log(index, row.name);
            },

            deleteCategory(row) {
                console.log(row)
                this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var that=this;
                    this.$ajax.post('/jz/category/deleteCategoryById?id='+row.id).then(function (resp) {
                        //console.log(resp.data);
                        if(resp.data.status==200){
                            that.$message({
                                message: '删除成功，请刷新！',
                                type: 'success'
                            });
                        }
                        if(resp.data.status==204){
                            that.$message.error('删除失败，请重试！');
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            handleAvatarSuccess(res, file) {
                console.log(res.photo)
                this.$set(this.productForm,"photo", res.photo)
                // this.imageUrl = URL.createObjectURL(file.raw);
            },

            handleAvatarSuccess3(res, file){
                console.log(res.video)
                this.$set(this.productForm,"video", res.video)
                if(res.video){
                    this.$message({
                        message: '上传视频成功',
                        type: 'success'
                    });
                } else {
                    this.$message.error('上传视频失败');
                }
            },

            handleAvatarSuccess2(res, file) {
                console.log(res.photo)
                this.$set(this.newProductForm,"photo", res.photo)
                // this.imageUrl = URL.createObjectURL(file.raw);
            },
            modifyCategoryName(){
               // this.dialogInputVisible1=false;
                var that=this;
                this.$ajax.post('/jz/category/updateCategory?number='+this.rowNumber+'&name='+this.modifyCaName).then(function (resp) {
                    //console.log(resp.data);
                    if(resp.data.status==200){
                        that.$message({
                            message: '修改成功，请刷新！',
                            type: 'success'
                        });
                        that.dialogVisible1=false
                    }
                    if(resp.data.status==204){
                        that.$message.error('修改失败，请重试！');
                    }
                })
            },

            editProduct(row){
                this.dialogVisible2=true;
                console.log(row)
                this.newProductForm=row
                console.log(this.allCategory[row.caid-1].name);
                this.defaultCategory=this.allCategory[row.caid-1].name;
                if(row.status==1){
                    this.defaultStatus='上架';
                } else{
                    this.defaultStatus='下架';
                }
            },

            deleteProduct(row){
                //this.dialogVisible4=true;
                console.log(row)
                this.$confirm('此操作将永久删除该产品, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var that=this;
                    this.$ajax.post('/jz/product/deleteProductById?id='+row.id).then(function (resp) {
                        //console.log(resp.data);
                        if(resp.data.status==200){
                            that.$message({
                                message: '删除成功，请刷新！',
                                type: 'success'
                            });
                        }
                        if(resp.data.status==204){
                            that.$message.error('删除失败，请重试！');
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //分页获取所有分类
            page(currentPage){
                var that = this;
                this.$ajax.get('http://localhost:8080/jz/category/showAllCategoryByPage?currentPage='+currentPage).then(function (resp) {
                   // console.log(resp.data);
                    that.total=resp.data.totalCount;
                    that.allCategory=resp.data.categoryList;
                })
            },

            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let params=this.productForm
                        let url='http://localhost:8080/jz/product/addProduct'
                        this.$axios.post(url,params).then(res =>{
                            // console.log('请求成功')
                            console.log(res)
                            this.$message({
                                message: '添加成功，请刷新！',
                                type: 'success'
                            });
                            //this.productForm=null
                        }).catch(error =>{
                            this.$message.error('添加失败');
                            console.log(error )
                        })

                    } else {
                        console.log('error submit!!');
                        //return false;
                    }
                    this.productDialogVisible=false;
                });
            },

            statusChange(value){
                this.newProductForm.status=value;
            },

            categoryChange(value){
                this.newProductForm.caid=value;
            },

            submitNewForm (formName) {
               // console.log(this.defaultStatus+"sdfsdfd")
                console.log(this.newProductForm)
                this.$refs[formName][0].validate((valid) => {
                    if (valid) {
                        let params=this.newProductForm
                        let url='http://localhost:8080/jz/product/modifyProduct'
                        this.$axios.post(url,params).then(res =>{
                            // console.log('请求成功')
                            console.log(res)
                            this.$message({
                                message: '修改成功，请刷新！',
                                type: 'success'
                            });
                        }).catch(error =>{
                            // console.log('请求失败')
                            console.log(error )
                            this.$message.error('修改失败');
                        })

                    } else {
                        console.log('error submit!!');
                        //return false;
                    }
                    this.dialogVisible2=false;
                });
            },

            changeProductStatus(row){
                console.log(row);
                var that=this;
                this.$ajax.get('http://localhost:8080/jz/product/changeProductStatus?id='+row.id).then(function (resp) {
                    console.log(resp.data);
                    if(resp.data.status==200){
                        that.$message({
                            message: '状态已更改，请刷新！',
                            type: 'success'
                        });
                    }
                    if(resp.data.status==204){
                        that.$message({
                            message: '状态更改失败',
                            type: 'error'
                        });
                    }
                    if(resp.data.status==205){
                        that.$message({
                            message: '该产品不存在',
                            type: 'error'
                        });
                    }
                })
            }
        }
    }
</script>

<style scoped>
    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
